package dashboard;

import java.io.IOException;
import java.io.ObjectStreamException;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.*;

@SuppressWarnings("serial")

public class FavouriteServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {
		
		User cUser1 = (User) req.getSession().getAttribute("user");
		User cUser = UserRegistry.getInstance().getUser(cUser1.getUserName());
		String action = req.getParameter("action");
		
		if(action.equals("addfav"))
		{
			if(!cUser.getFavourites().contains(req.getParameter("userName")) && !cUser.getUserName().equals(req.getParameter("username")))
			{
			cUser.addFavourite(req.getParameter("userName"));
			UserRegistry.getInstance().addUser(cUser);
			resp.sendRedirect("dashboard.jsp?I=favadded");
			}
			else
				resp.sendRedirect("dashboard.jsp?I=alreadyfav");
		}
		else if(action.equals("removefav"))
		{
			cUser.removeFavourite(req.getParameter("userName"));
			UserRegistry.getInstance().addUser(cUser);
			resp.sendRedirect("dashboard.jsp?I=favremoved");
		}
		
		else if(action.equals("view"))
		{
		List<User> result = new ArrayList<User>();
			List<String> favorites = cUser.getFavourites();
			for(String fav: favorites){
				result.add(UserRegistry.getInstance().getUser(fav));
			}
			HttpSession session =req.getSession();
			session.setAttribute("fav",result);
			resp.sendRedirect("Favorites.jsp?action=view");
		}
	}
}